import { RawData, WebSocket } from "ws";
import { MsgParser } from "../common/MsgParser";

/**
 * 连接
 */
export class Connection {
    onMsg: Function | null = null;
    onClose: Function | null = null;

    protected _ws: WebSocket | null = null;
    protected _msgParse: MsgParser | null = null;

    constructor(ws: WebSocket) {
        this._ws = ws;
        this._ws.on('message', this._onmsg.bind(this))
        this._ws.on('close', this._onclose.bind(this))
        this._ws.on('error', this._onerror.bind(this))

        this._msgParse = new MsgParser();
    }

    
    protected _onerror(e: Error) {
    }
    protected _onclose(code: number, reason: Buffer) {
    }
    protected _onmsg(data: RawData, isBinary: boolean) {
    }

    protected send (cmd:number, data: Uint8Array) {
        const sendData = this._msgParse!.wrap(cmd, data);
        if (sendData)
            this._ws!.send(sendData);
    }
}